package com.bluefish.bltuan.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bluefish.bltuan.dao.ContentDao;
import com.bluefish.bltuan.module.cms.Content;
import com.bluefish.bltuan.module.cms.ContentType;
import com.bluefish.bltuan.service.ContentService;

@Service
@Transactional
public class ContentServiceImpl implements ContentService{

	private ContentDao contentDao;
	
	public void delete(Content t) {
		int pos = t.getPosition();
		ContentType type = t.getType();
		this.contentDao.delete(t);
		this.contentDao.updatePositionAfter(pos, type);
	}

	public Content findById(Integer id) {
		return this.contentDao.findById(id);
	}

	public void save(Content content) {
		if(content != null){
			int pos = this.contentDao.countByType(content.getType());
			content.setPosition(pos+1);
			this.contentDao.save(content);
		}
	}

	public void update(Content t) {
		this.contentDao.update(t);
	}
	
	public void saveOrUpdate(Content content) {
		if(content != null){
			if(content.getPosition() == 0){
				int pos = this.contentDao.countByType(content.getType());
				content.setPosition(pos+1);
			}
			this.contentDao.saveOrUpdate(content);
		}
	}
	
	public List<Content> list(ContentType type) {
		return this.contentDao.listByType(type);
	}

	public List<Content> listFriendlylinks() {
		return list(ContentType.FRIENDLY_LINK);
	}
	
	public List<Content> listIntroductions() {
		return list(ContentType.INTRODUCTION);
	}
	
	public List<Content> listQuestions() {
		return list(ContentType.QUESTION);
	}
	
	public List<Content> listHelps() {
		return list(ContentType.HELP);
	}
	
	public Content getByNick(String nick) {
		List<Content> contents = this.contentDao.listByNick(nick);
		return contents != null && contents.size() > 0 ? contents.get(0) : null;
	}
	
	public void setContentDao(ContentDao contentDao) {
		this.contentDao = contentDao;
	}

}
